﻿
using MimeKit;
using MimeKit.Text;
using System.Net.Mail;

namespace Email.Services
{
    public class EmailHelper2
    {

        public EmailHelper2()
        {
                
        }

        const string mailFrom = "kdc@hellorr.com";
        const string mailTo = "392090057@qq.com";
        const string mailFromAccount = "service@hellorr.com";
        const string mailPassword = "Service@@6868";
        const string mailServer = "smtphz.qiye.163.com";
        const int mailPort = 587;

        public void SendEmail()
        {
            Console.WriteLine("开始发送邮件...");
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("信息系统管理员", mailFromAccount));
            message.To.Add(new MailboxAddress(mailTo, mailTo));
            message.Subject = string.Format("C#自动发送邮件测试 From geffzhang TO {0}", mailTo);

            var plain = new TextPart("plain")
            {
                Text = @"20220101！"
            };
            var html = new TextPart("html")
            {
                Text = @"您本次登录需要验证码; <br/> 请输入验证码 123654 ，本次验证码 10 分钟内有效！"
            };
            var alternative = new Multipart("alternative");
            alternative.Add(plain);
            alternative.Add(html);
             
            var multipart = new Multipart("mixed");
            multipart.Add(alternative);
            message.Body = multipart;

            try
            {
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    //HTTPS邮件服务器用587端口，HTTP默认25端口
                    client.Connect(mailServer, mailPort, false);
                    // 禁用XOAUTH2认证
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    // 注意：仅在SMTP服务器需要身份验证时才需要
                    client.Authenticate(mailFromAccount, mailPassword);
                    client.Send(message);
                    client.Disconnect(true);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

    }

}
